package com.ssh.util.image;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;

/**
 * 图片操作类，将内容写入图片并保存。
 *
 * @author 单文超,
 * @since 2011-12-06 12:05:31
 */
public class BuildImg {
    private List<ImgElement> imgElements;
    private String templatePath;          // 模板图片路径（包括名称）
	private String outputPath;            // 生成图片的存放路径
    private String outputName;            // 生成图片的名称
    private String format = "jpg";        // 图片格式

    public synchronized void build() throws Exception {
    	// 获取模板图片
    	BufferedImage image = ImageIO.read(new File(this.getTemplatePath()));

		String outputPath = this.getOutputPath();
		
		// 从图片中获取编辑器
		Graphics2D graphics = (Graphics2D) image.createGraphics();
		graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		
		for(ImgElement imgElement : imgElements) {
			graphics.setFont(imgElement.getElementFont());
			graphics.setColor(imgElement.getElementColor());

            switch (imgElement.getElementType()){
                default:
                    graphics.drawString((String) imgElement.getElementContent(), imgElement.getStartX(), imgElement.getStartY());
                case ImgElement.STRING_ELEMENT:
                	String context = imgElement.getElementContent().toString();
                    int fontSize = imgElement.getElementFont().getSize();
                    int x = imgElement.getStartX();
                    int y = imgElement.getStartY();
                    int breakWidth = imgElement.getBreakWidth();
                    int t = 1;
                    StringBuffer lineContext = new StringBuffer();
                    for(int i = 0; i < context.length(); i++) {
                    	if((t * fontSize) > breakWidth) {
                    		graphics.drawString(lineContext.toString(), x, y);
                    		lineContext.setLength(0);
                    		Character str = context.charAt(i);
                    		lineContext.append(str);
                    		t = 1;
                    		y = y + fontSize;
                    		
                    	} else {
                    		Character str1 = context.charAt(i);
                    		lineContext.append(str1);
                    	}
                    	
                    	if(i == (context.length() -1)) {
                    		graphics.drawString(lineContext.toString(), x, y);
                    	}
                    	t++;
                    }
                    break;
                case ImgElement.IMAGE_ELEMENT:
                    BufferedImage imageContent = (BufferedImage) imgElement.getElementContent();
                    graphics.drawImage((Image) imgElement.getElementContent(), imgElement.getStartX(),
						imgElement.getStartY(), imageContent.getWidth(),
						imageContent.getHeight(), null);
                    break;
                case ImgElement.RECT_ELEMENT:
                    graphics.draw3DRect(imgElement.getStartX(), imgElement.getStartY(), imgElement.getWidth(), imgElement.getHeight(),false);
                    break;
            }
		}
		
		graphics.dispose();

        File dirFile = new File(outputPath);
        if(!dirFile.exists())dirFile.mkdirs();
		ImageIO.write(image, this.format, new File(outputPath
				+ this.outputName + "." + this.format));
    }
    
    /**
     * 获取字符长度，一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
     * @param text
     * @return 字符长度，如：text="中国",返回 2；text="test",返回 2；text="中国ABC",返回 4.
     */
    public static int getLength(String text) {
        int textLength = text.length();
        int length = textLength;
        for (int i = 0; i < textLength; i++) {
            if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
                length++;
            }
        }
        return (length % 2 == 0) ? length / 2 : length / 2 + 1;
    }

    public List<ImgElement> getImgElements() {
        return imgElements;
    }

    public void setImgElements(List<ImgElement> imgElements) {
        this.imgElements = imgElements;
    }

    public String getTemplatePath() {
        return templatePath;
    }

    public void setTemplatePath(String templatePath) {
        this.templatePath = templatePath;
    }

    public String getOutputPath() {
        return outputPath;
    }

    public void setOutputPath(String outputPath) {
        this.outputPath = outputPath;
    }

    public String getOutputName() {
        return outputName;
    }

    public void setOutputName(String outputName) {
        this.outputName = outputName;
    }

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}
}
